<template>
    <el-container>
        <el-header class="sa-header">
            <div class="sa-title sa-flex sa-row-between">
                <div class="label sa-flex">
                    <span class="left">我的选品库</span>

                    <search-condition :conditionLabel="filterParams.conditionLabel"
                        @deleteFilter="deleteFilter"></search-condition>
                </div>
                <div>
                    <el-button class="sa-button-refresh" icon="Search" @click="openFilter"></el-button>
                </div>
            </div>
            <el-tabs class="sa-tabs" v-model="filterParams.data.from" @tab-change="getData(1)">
                <el-tab-pane label="1688" name="1688"></el-tab-pane>
                <el-tab-pane label="云中鹤" name="yzh"></el-tab-pane>
            </el-tabs>
        </el-header>
        <el-main class="sa-p-0" v-loading="store.loading">
            <div class="store">
                <template v-if="filterParams.data.from !== '1688'">
                    <div class="store-item" v-for="(item) in store.lists" :key="item.id">
                        <div class="title">{{ item.name }}</div>
                        <div class="desc">
                            <div class="desc-left">供应商/{{ item.from_text }}</div>
                            <!-- <div class="desc-right">创建人/{{ item.name }}</div> -->
                        </div>
                        <div class="item-cont">
                            <div class="item-num">
                                {{ item.num - item.up_num }}/{{ item.num }}
                            </div>
                            <div class="item-status">
                                未上架/已选数量
                            </div>
                        </div>
                        <div class="item-action">
                            <el-button class="sa-button-refresh" icon="Plus" @click="goToSelectGoods(item,'yzh')">选品</el-button>
                            <el-button class="sa-button-refresh" icon="Edit" @click="editStore(item,'yzh')">修改选品库</el-button>
                            <el-button class="sa-button-refresh" icon="View" @click="viewGoods(item,'yzh')">查看商品</el-button>
                        </div>
                        <div class="posit" @click="delItem(item,'yzh')">
                            <el-icon size="25">
                                <Close />
                            </el-icon>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <div class="store-item" v-for="(item) in store.lists" :key="item.id">
                        <div class="title">{{ item.name }}</div>
                        <div class="desc">
                            <div class="desc-left">供应商/{{ item.supplier }}</div>
                            <!-- <div class="desc-right">创建人/{{ item.name }}</div> -->
                        </div>
                        <div class="item-cont">
                            <div class="item-num">
                                {{ item.no_up }}/{{ item.g_count }}
                                  <!-- {{ pageData.total }} -->
                            </div>
                            <div class="item-status">
                                <!-- 未上架/已选数量 -->
                                未上架/已选数量
                            </div>
                        </div>
                        <div class="item-action">
                            <el-button class="sa-button-refresh" icon="Plus" @click="goToSelectGoods(item,'1688')">选品</el-button>
                            <el-button class="sa-button-refresh" icon="Edit" @click="editStore(item,'1688')">修改选品库</el-button>
                            <el-button class="sa-button-refresh" icon="View" @click="viewGoods(item,'1688')">查看商品</el-button>
                        </div>
                        <div class="posit" @click="delItem(item,'1688')">
                            <el-icon size="25">
                                <Close />
                            </el-icon>
                        </div>
                    </div>
                </template>
                <div class="store-item add" @click="addStore">
                    <div class="adds">
                        <el-icon size="25">
                            <Plus />
                        </el-icon>
                        <div>新建</div>
                    </div>
                </div>
            </div>
        </el-main>
        <sa-view-bar>
            <template #right>
                <sa-pagination :pageData="pageData" @updateFn="getData" :pagesize="[10,20]" />
            </template>
        </sa-view-bar>
        <el-dialog v-model="dialogVisible" title="新增选品库" width="500" :before-close="handleClose">
            <el-form :model="store.form" label-width="auto" style="max-width: 600px">
                <el-form-item label="供应商">
                    <el-select v-model="store.form.from" placeholder="请选择供应商" disabled>
                        <el-option v-for="(item,index) in options" :key="index"  :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="产品库名称">
                    <el-input v-model="store.form.name" placeholder="请输入产品库名称" maxlength="15" />
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="addApply" v-if="store.type=='add'"> 确认 </el-button>
                    <el-button type="primary" @click="editApplyStore" v-if="store.type=='edit'"> 确认 </el-button>
                </div>
            </template>
        </el-dialog>
    </el-container>
</template>
<script>
export default {
    name: 'supplychian.admin.goods.store',
};
</script>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { usePagination, useModal } from '@/sheep/hooks';
import { useSearch } from '@/sheep/components/sa-table/sa-search/useSearch';
import { cloneDeep } from 'lodash';
import { ElMessage } from 'element-plus';
import $storage from '@/sheep/utils/storage';
import router from '@/sheep/router';
import {api} from '../goods.service'
const options=ref([
    {
        label:"1688",
        value:1
    },
    {
        label:"淘宝",
        value:2 
    }
])
const store = reactive({
    loading: false,
    supplierList:[],
    type:"add",
    lists: [
       
    ],
    form: {
        name: "",
        from: "",
        id:""
    }
});
// 修改选品库
const editStore=async(item)=>{
    store.form.name=item.name
    store.form.from=item.from || item.supplier
    store.form.id=item.id
    dialogVisible.value = true;
    store.type="edit"
}
const addStore=()=>{
    store.type="add"
    let tempSearch = cloneDeep(filterParams.data);
    store.form.from = tempSearch.from
    dialogVisible.value = true;
}
// 查看选品库商品
const viewGoods=async(item)=>{
    router.push({
        name:"supplychian.admin.goods.list",
        query:{
            id:item.id,
            type:'recyclebin',
            from:item.from || '1688'
        }
    })
}
const editApplyStore=async()=>{
    if(!store.form.name){
        store.form.name = formatDate(new Date())
    }
    let tempSearch = cloneDeep(filterParams.data);
    if(tempSearch.from === '1688'){
        const bodydata = {
            "name": store.form.name,
            "supplier": "1688",
            "id": store.form.id,
        }
        const {error,data}= await api.shopedit_category(bodydata)
        if(error===0){
            ElMessage.success("修改成功")
            dialogVisible.value = false;
            store.form = {
                name: "",
                from: "",
                id:''
            }
            getData()
        }
    }else{
        const {error,data}= await api.editStore(store.form)
        if(error===0){
            ElMessage.success("修改成功")
            dialogVisible.value = false;
            store.form = {
                name: "",
                from: "",
                id:'',
            }
            getData()
        }
    }
}
// 添加选品库
const addApply=async()=>{
    if(!store.form.name){
        store.form.name = formatDate(new Date())
    }
    let tempSearch = cloneDeep(filterParams.data);
    if(tempSearch.from === '1688'){
        const bodydata = {
            "name": store.form.name,
            "supplier": "1688"
        }
        const {error,data} = await api.shopadd_category(bodydata)
        if(error===0){
            ElMessage.success("添加成功")
            dialogVisible.value = false;
            store.form = {
                name: "",
                from: ""
            }
            getData()
        }
    }else{
        const {error,data} = await api.addStore(store.form)
        if(error===0){
            ElMessage.success("添加成功")
            dialogVisible.value = false;
            store.form = {
                name: "",
                from: ""
            }
            getData()
        }
    }
    
}
const goToSelectGoods=(item)=>{
    router.push({
        name:"supplychian.admin.goods.store.addgoods",
        query:{
            id:item.id,
            type:'add',
            name:item.from || '1688'
        }
    })
}
const dialogVisible = ref(false);

const filterParams = reactive({
    tools: {

        search: {
            type: 'tinput',
            label: '商品库名称',
            field: 'search',
            value: '',
        },
        from: {
            type: 'tselect',
            label: '请选择供应商',
            field: 'from',
            multiple: false,
            value: "yzh",
            clearable:'clearable',
            clearable_flag:false,
            options: {
                data: [
                   
                ],
            },
        },

    },
    data: {
        from: '1688',
        search:'',


    },
    conditionLabel: {},
});

const { openFilter, deleteFilter } = useSearch({ filterParams, getData });

const { pageData } = usePagination();

const handleClose = () => {
    dialogVisible.value = false;
    store.form = {
        name: "",
        from: ""
    }
};
// 删除选品库
const delItem = async(el,qd) => {
    if(qd === 'yzh'){
        if(el.num > 0){
            ElMessage.warning('删除失败，选品库中存在商品');
            return
        }
        const res = await api.delChannelHouse(el.id)
        ElMessage.warning('删除成功');
        getData()
    }else{
        if(el.g_count > 0){
            ElMessage.warning('删除失败，选品库中存在商品');
            return
        }
        const res = await api.shopcategory_del({id:el.id})
        ElMessage.warning('删除成功');
        getData()
        
    }
    
    // store.lists = store.lists.filter(item => item.id !== el.id);
    
}
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 
// 获取供应商
const getSupplier = async () => {
    // const { error, data } = await api.supplyList();
    // if (error === 0) {
    //     store.supplierList.push(data);
    //     // 将对象转换为数组格式
    //     filterParams.tools.from.options.data = Object.entries(data).map(([key, value]) => ({
    //         label: value,
    //         value: key
    //     }));
    //     options.value= filterParams.tools.from.options.data
    //     options.value.push({
    //         label:'1688',
    //         value:'1688',
    //     })
    // }   `q!aswdx czvf                                                                                                              `


    const data = {
        yzh:'云中鹤'
    }
    store.supplierList.push(data);
    filterParams.tools.from.options.data = Object.entries(data).map(([key, value]) => ({
            label: value,
            value: key
        }));
        options.value= filterParams.tools.from.options.data
    options.value.push({
            label:'1688',
            value:'1688',
        })
        
}
async function getData(page) {
    store.loading = true
    store.lists = []
    if (page) pageData.page = page;
    let tempSearch = cloneDeep(filterParams.data);
    if(tempSearch.from === '1688'){
        const { error, data } = await api.shopcategory_list({
            page: pageData.page,
            limit: pageData.list_rows,
            // from: tempSearch.from,
            name: tempSearch.search,
        });
        store.loading = false
        if (error === 0) {
            pageData.page = Number(data.current_page);
            pageData.list_rows = data.per_page;
            pageData.total = data.total;
            store.lists = data.data
        }
    }else{
        const { error, data } = await api.getStoreList({
            page: pageData.page,
            list_rows: pageData.list_rows,
            from: tempSearch.from,
            search: tempSearch.search,
        });
        store.loading = false
        if (error === 0) {
            pageData.page = data.current_page;
            pageData.list_rows = data.per_page;
            pageData.total = data.total;
            store.lists=data.data
        }
    }
    
    
}


onMounted(() => {
    getData();
    getSupplier()
});
</script>
<style lang="scss" scoped>
.store {
    padding: 10px;
    width: 100%;
    height: 100px;
    display: flex;
    justify-content: start;
    align-items: start;
    flex-wrap: wrap;

    .store-item {
        width: 320px;
        padding: 10px;
        height: 200px;
        background: #f2f2f2;
        margin: 10px;
        border-radius: 10px;
        position: relative;

        .title {
            font-size: 20px;
            font-weight: bold;
        }

        .desc {
            margin-top: 5px;
            display: flex;
            font-size: 14px;
            color: #999;

            .desc-left {
                margin-right: 20px;
            }

        }

        .item-cont {
            margin-top: 20px;
            text-align: center;

            .item-num {
                color: #0099fe;
                font-size: 20px;
                font-weight: bold;
            }

            .item-status {
                font-size: 14px;
                margin-top: 5px;
            }
        }

        .item-action {
            margin-top: 20px;
            text-align: center;
            display: flex;
            justify-content: space-between;

            .sa-button-refresh {
                width: 40%;
            }
        }

        .posit {
            position: absolute;
            right: 5px;
            top: 5px;
        }
    }

    .add {
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>